package com.yunfeng.master.common.utils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    // 数据库查询专用线程池
    @Bean("dbQueryExecutor")
    public ExecutorService dbQueryExecutor() {
        return createThreadPool("DB-Query-", 10, 20, 100);
    }

    // IO密集型任务线程池（如外部API调用）
    @Bean("ioTaskExecutor")
    public ExecutorService ioTaskExecutor() {
        return createThreadPool("IO-Task-", 20, 50, 200);
    }

    // 计算密集型任务线程池（核心数相关）
    @Bean("computeExecutor")
    public ExecutorService computeExecutor() {
        int cores = Runtime.getRuntime().availableProcessors();
        return createThreadPool("Compute-", cores, cores, 50);
    }


    @Bean("queryThreadPool")
    public Executor queryThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数 = CPU核心数 * 2
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 2);
        // 最大线程数 = 核心线程数 * 3（根据IO密集型任务特点）
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 3);
        // 队列容量 = 200（防止OOM）
        executor.setQueueCapacity(200);
        // 线程名前缀
        executor.setThreadNamePrefix("query-pool-");
        // 拒绝策略：由调用线程处理（保障数据不丢失）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    private ThreadPoolExecutor createThreadPool(String namePrefix,
                                                int coreSize,
                                                int maxSize,
                                                int queueCapacity) {
        return new ThreadPoolExecutor(
                coreSize,
                maxSize,
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(queueCapacity),
                r -> new Thread(r, namePrefix + r.hashCode()),
                new ThreadPoolExecutor.CallerRunsPolicy() // 饱和策略
        ) {
            // 监控钩子：记录任务耗时
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                // 这里可以记录任务耗时到监控系统
            }
        };
    }

    @Bean("optimizedQueryExecutor")
    public ThreadPoolTaskExecutor queryExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 根据服务器CPU核数动态设置
        int core = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(core * 2);       // IO密集型任务设置为2N
        executor.setMaxPoolSize(core * 4);        // 突发流量缓冲
        executor.setQueueCapacity(1000);           // 使用有界队列防止内存溢出
        executor.setThreadNamePrefix("query-opt-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //executor.setTaskDecorator(new MdcTaskDecorator()); // 支持日志链路追踪
        executor.setWaitForTasksToCompleteOnShutdown(true); // 优雅停机
        executor.setAwaitTerminationSeconds(30);
        executor.initialize();
        return executor;
    }


}